# Import Flask's global request context 'g' and the current request object.
from flask import g, request

# Import a custom context manager for ignoring exceptions.
from .exception import ignore_exception


def get_request_id(default=None):
    """
    Retrieves the request ID from the current request context.

    It first attempts to get the ID from the 'x_request_id' header.
    If that fails, it tries to get it from Flask's global 'g' object.
    If both fail, it returns the provided default value.

    This function is designed to work safely both inside and outside of a
    Flask request context by ignoring potential RuntimeError exceptions.

    :param default: The value to return if no request ID is found.
    :return: The request ID string or the default value.
    """
    # Initialize the request_id variable.
    request_id = None

    # Use a context manager to suppress any exceptions that might occur,
    # for example, if this function is called outside of an active Flask request context.
    with ignore_exception:
        # Check if the request object and its headers are available.
        if request and request.headers:
            # Attempt to get the request ID from the 'x_request_id' HTTP header.
            if 'x_request_id' in request.headers:
                request_id = request.headers.get('x_request_id')
        # If the request ID was not found in the headers, try to get it from
        # the Flask global context 'g', where it might have been stored by middleware.
        if not request_id:
            request_id = g.x_request_id

    # If the request ID is still not found after checking both sources,
    # fall back to the provided default value.
    if not request_id:
        request_id = default

    # Return the found request ID or the default value.
    return request_id
